package me.shurufa.fragments;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.kaopiz.kprogresshud.KProgressHUD;

import java.io.File;
import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import me.shurufa.R;
import me.shurufa.model.AddDigestBean;
import me.shurufa.model.TransfromResponse;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.IdentifyImageResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.smoothcamera.util.DeviceUtil;
import me.shurufa.widget.smoothcamera.util.ImageUtils;

/**
 * 作者 : andy
 * 日期 : 16/3/9 10:31
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 内容简介 Fragment
 */
public class DigestPreviewFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.iv_crop_src)
    ImageView iv_crop_src;
    @Bind(R.id.et_digest_content)
    EditText et_digest_content;
    @Bind(R.id.cb_save_image)
    CheckBox cb_save_image;

    @Bind(R.id.cb_save_text)
    CheckBox cb_save_text;
    @Bind(R.id.tv_save_text)
    TextView tv_save_text;
    @Bind(R.id.tv_save_image)
    TextView tv_save_image;

    private KProgressHUD kProgressHUD;
    private String mImageFilePath;
    private boolean digestContent;
    private AddDigestBean mAddDigestBean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mImageFilePath = getArguments().getString(Constants.EXTRA_CAMERA_PHOTO);
            mAddDigestBean = (AddDigestBean) getArguments().getSerializable(Constants.ARG_ADD_DIGEST);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_digest_preview, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 创建
     *
     * @param absImageFilePath
     * @return
     */
    public static DigestPreviewFragment newInstance(String absImageFilePath, AddDigestBean addDigestBean) {
        DigestPreviewFragment fragment = new DigestPreviewFragment();
        Bundle args = new Bundle();
        args.putString(Constants.EXTRA_CAMERA_PHOTO, absImageFilePath);
        args.putSerializable(Constants.ARG_ADD_DIGEST, addDigestBean);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);

        // 默认保存识别的文字
        cb_save_text.setChecked(true);

        // 显示图片
        showImage();

        // 请求图像识别
        reqImageIdentify();

        // 初始化监听器
        initListener();
    }

    private void initListener() {
        tv_save_text.setOnClickListener(this);
        tv_save_image.setOnClickListener(this);

        cb_save_text.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cb_save_image.setChecked(false);
                }
            }
        });

        cb_save_image.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cb_save_text.setChecked(false);
                }
            }
        });
    }

    /**
     * 显示图片
     */
    private void showImage() {
        Bitmap bitmap= ImageUtils.decodeBitmapWithOrientationMax(mImageFilePath,
                DeviceUtil.getScreenWidthForCamera(getActivity()) / 8,
                DeviceUtil.getScreenHeight(getActivity()) / 8);

        iv_crop_src.setImageBitmap(bitmap);
    }

    /**
     * 请求图像识别
     */
    public void reqImageIdentify() {
        try {
            File file = new File(mImageFilePath);
            RequestParams params = new RequestParams();
            params.addFormDataPart("image", file);

            HttpRequest.post(API.IDENTIFY_IMAGE_TO_TEXT, params, new HttpCallback<IdentifyImageResp>(getActivity(), R.string.identify) {

                @Override
                public void onRespSuccess(IdentifyImageResp resp) {
                    if (!TextUtils.isEmpty(resp.content)) {
                        mAddDigestBean.screenShot = resp.url;
                        String resultString = resp.content.trim().toString();
                        resultString = resultString.replace("\n", " ");
                        et_digest_content.setText(resultString.trim());
                        Utils.moveCursorToLast(et_digest_content);
                    } else {
                        mAddDigestBean.screenShot = resp.url;
                        Utils.showToast("未找到内容");
                    }
                }

                @Override
                public void onRespFailure(IdentifyImageResp resp) {
                    Utils.showToast("识别失败");
                }
            });
        } catch (Exception e) {
            Utils.showToast(R.string.sys_err);
        }
    }

    /**
     * 识别返回结果
     *
     * @param s
     */
    private void doResult(String s) {
        if (!TextUtils.isEmpty(s)) {
            LogUtils.kLog().d(s);
        }
        TransfromResponse result = null;
        try {
            if (!TextUtils.isEmpty(s)) {
                result = Global.getGson().fromJson(s, TransfromResponse.class);
            } else {
                result = null;
            }
            if (result != null && result.success) {
                // if (result.data != null && !TextUtils.isEmpty(result.text.toString().trim())) {
                if (!TextUtils.isEmpty(result.text.toString().trim())) {
                    mAddDigestBean.screenShot = result.url;
                    String resultString = result.text.toString();
                    resultString = resultString.replace("\n", " ");
                    et_digest_content.setText(resultString.trim());
                    Utils.moveCursorToLast(et_digest_content);
                } else {
                    mAddDigestBean.screenShot = result.url;
                    Utils.showToast("未找到内容");
                }
            } else {
                if (result != null) {
                    Utils.showToast(result.error.message);
                } else {
                    Utils.showToast("提交失败");
                }
            }
        } catch (Exception e) {
        } finally {
            if (kProgressHUD != null) {
                kProgressHUD.dismiss();
            }
        }
    }

    /**
     * @return 是否能进行下一步 判断书摘内容是否为空
     */
    public boolean canDoNext() {
        String content = et_digest_content.getText().toString();
        return !TextUtils.isEmpty(content);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_save_text:
                cb_save_text.toggle();
                break;
            case R.id.tv_save_image:
                cb_save_image.toggle();
                break;
        }
    }

    /**
     * 获得书摘内容
     *
     * @return
     */
    public String getDigestContent() {
        return et_digest_content.getText().toString();
    }

    /**
     * 获得图片书摘url
     * @return
     */
    public String getDigestImageUrl() {
        return mAddDigestBean == null ? "" : mAddDigestBean.screenShot;
    }

    /*public void handle() {
        if (cb_save_image.isChecked()) {
            saveImage();
        }
    }*/

    private void saveImage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    BitmapDrawable bmpDrawable = (BitmapDrawable) iv_crop_src.getDrawable();
                    Utils.saveFile(getActivity(), bmpDrawable.getBitmap());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 获得书摘的类型 0是文本书摘， 1是图片书摘
     * @return
     */
    public int getDigestType() {
        return cb_save_text.isChecked() ? 0 : 1;
    }
}
